import { Layout } from 'antd';
import {  ThemeProvider } from 'antd-style';
import { useCallback, useEffect, useState } from 'react';

import { Background } from './components/Background/Background.tsx';
import { Menu } from './components/Menu/Menu.tsx';
import { useProvider } from './hooks/useProvider.tsx';
import { PageMain } from './pages/Main/PageMain.tsx';
import { PageStart } from './pages/Start/PageStart.tsx';
import  { getThemeColors, getCustomTokens } from './theming/colors';

import type { LoadState } from './types.ts';

interface NewToken {
    startPageBg: string;
    siderBackground: string;
    siderBorder: string;
    brandColor: string;
}

// By extending the CustomToken object type definition for antd-style, you can add corresponding token objects to useTheme
declare module 'antd-style' {
    export interface CustomToken extends NewToken {}
}

function App () {
    const [loadState, setLoadState] = useState<LoadState>('offline');
    const [connected, setConnected] = useState(false);
    const { error, getProviderAndAccount } = useProvider();

    const handleClickConnect = useCallback(async () => {

        setLoadState('loading');

        await getProviderAndAccount();

        if (error) {
            setLoadState('error');
            return;
        }

        setLoadState('connected');

    }, [error, getProviderAndAccount]);
    
    useEffect(() => {
        if (loadState === 'connected') {
            const timeoutId = setTimeout(() =>{
                setConnected(true);
            }, 2000);
            
            return () => clearTimeout(timeoutId);
        }
    }, [loadState]);

    return (
        <ThemeProvider
            defaultThemeMode={'auto'}
            theme={getThemeColors}
            customToken={getCustomTokens}
        >
            { !connected && <Background /> }
            <Menu/>
            <Layout>
                {
                    !connected
                        ? <PageStart
                            handleClickConnect={handleClickConnect}
                            loadState={loadState}
                        />
                        : 
                        <PageMain />
                }

            </Layout>

        </ThemeProvider>
    );
}

export default App;
